from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash
from datetime import datetime, date, time
from decimal import Decimal
from models import db, Employee, AttendanceRecord, PayrollRecord, User

def init_db(app):
    """初始化数据库"""
    with app.app_context():
        try:
            # 创建所有表
            db.create_all()
            print("数据库表创建成功")
            
            # 检查是否已有数据
            if User.query.first() is None:
                seed_database()
            else:
                print("数据库已有数据，跳过初始化")
        except Exception as e:
            print(f"数据库初始化失败: {e}")
            raise

def seed_database():
    """填充示例数据"""
    print("开始填充示例数据...")
    
    # 创建默认管理员用户
    admin_user = User(
        username='admin',
        password_hash=generate_password_hash('admin123'),
        is_active=True
    )
    db.session.add(admin_user)
    
    # 创建示例员工数据
    employees_data = [
        {
            'name': '张三',
            'email': 'zhangsan@company.com',
            'position': '软件工程师',
            'department': '技术部',
            'hire_date': date(2023, 1, 15),
            'salary': 15000.00,
            'avatar': 'https://via.placeholder.com/150/6366F1/FFFFFF?text=张',
            'job_description': '负责前端开发，使用React和TypeScript构建用户界面。'
        },
        {
            'name': '李四',
            'email': 'lisi@company.com',
            'position': '产品经理',
            'department': '产品部',
            'hire_date': date(2022, 8, 20),
            'salary': 18000.00,
            'avatar': 'https://via.placeholder.com/150/10B981/FFFFFF?text=李',
            'job_description': '负责产品规划和需求分析，协调开发团队完成产品迭代。'
        },
        {
            'name': '王五',
            'email': 'wangwu@company.com',
            'position': 'UI设计师',
            'department': '设计部',
            'hire_date': date(2023, 3, 10),
            'salary': 12000.00,
            'avatar': 'https://via.placeholder.com/150/F59E0B/FFFFFF?text=王',
            'job_description': '负责用户界面设计，创建美观易用的产品界面。'
        },
        {
            'name': '赵六',
            'email': 'zhaoliu@company.com',
            'position': '后端工程师',
            'department': '技术部',
            'hire_date': date(2022, 11, 5),
            'salary': 16000.00,
            'avatar': 'https://via.placeholder.com/150/EF4444/FFFFFF?text=赵',
            'job_description': '负责后端API开发，使用Python Flask构建服务端应用。'
        },
        {
            'name': '钱七',
            'email': 'qianqi@company.com',
            'position': '测试工程师',
            'department': '技术部',
            'hire_date': date(2023, 5, 12),
            'salary': 13000.00,
            'avatar': 'https://via.placeholder.com/150/8B5CF6/FFFFFF?text=钱',
            'job_description': '负责软件测试，确保产品质量和用户体验。'
        },
        {
            'name': '孙八',
            'email': 'sunba@company.com',
            'position': '运营专员',
            'department': '运营部',
            'hire_date': date(2023, 2, 28),
            'salary': 11000.00,
            'avatar': 'https://via.placeholder.com/150/06B6D4/FFFFFF?text=孙',
            'job_description': '负责产品运营，制定运营策略和用户增长计划。'
        }
    ]
    
    employees = []
    for emp_data in employees_data:
        employee = Employee(**emp_data)
        employees.append(employee)
        db.session.add(employee)
    
    db.session.commit()
    print(f"已创建 {len(employees)} 名员工")
    
    # 创建示例考勤记录
    attendance_data = []
    today = date.today()
    
    for i, employee in enumerate(employees):
        # 为每个员工创建最近7天的考勤记录
        for days_ago in range(7):
            # 修复日期计算，避免未来日期
            record_date = date(today.year, today.month, max(1, today.day - days_ago))
            
            # 检查是否已存在该日期的记录
            existing = AttendanceRecord.query.filter_by(
                employee_id=employee.id,
                date=record_date
            ).first()
            
            if existing:
                continue  # 跳过已存在的记录
            
            # 随机生成考勤状态
            import random
            statuses = ['Present', 'Present', 'Present', 'Late', 'Absent']  # Present概率更高
            status = random.choice(statuses)
            
            clock_in = None
            clock_out = None
            
            if status == 'Present':
                clock_in = time(9, random.randint(0, 15))  # 9:00-9:15
                clock_out = time(18, random.randint(0, 30))  # 18:00-18:30
            elif status == 'Late':
                clock_in = time(9, random.randint(16, 45))  # 9:16-9:45
                clock_out = time(18, random.randint(0, 30))  # 18:00-18:30
            
            attendance = AttendanceRecord(
                employee_id=employee.id,
                date=record_date,
                status=status,
                clock_in=clock_in,
                clock_out=clock_out
            )
            attendance_data.append(attendance)
            db.session.add(attendance)
    
    db.session.commit()
    print(f"已创建 {len(attendance_data)} 条考勤记录")
    
    # 创建示例工资记录
    payroll_data = []
    current_month = datetime.now().strftime('%Y-%m')
    
    for employee in employees:
        # 为每个员工创建当前月的工资记录
        bonus = Decimal(str(random.randint(0, 3000)))  # 0-3000的随机奖金
        deductions = Decimal(str(random.randint(0, 500)))  # 0-500的随机扣款
        net_pay = employee.salary + bonus - deductions
        
        payroll = PayrollRecord(
            employee_id=employee.id,
            pay_period=current_month,
            base_salary=employee.salary,
            bonus=bonus,
            deductions=deductions,
            net_pay=net_pay
        )
        payroll_data.append(payroll)
        db.session.add(payroll)
    
    db.session.commit()
    print(f"已创建 {len(payroll_data)} 条工资记录")
    
    print("数据库初始化完成！")
    print("默认管理员账号: admin / admin123")

def reset_database(app):
    """重置数据库（删除所有数据）"""
    with app.app_context():
        db.drop_all()
        db.create_all()
        seed_database()
        print("数据库已重置并重新填充示例数据")

if __name__ == '__main__':
    from app import create_app
    app = create_app()
    init_db(app)